package com.lee.rpc.protocal.spring.service;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import com.lee.rpc.protocal.core.RpcRequest;

public class Mediator {

	private volatile static Mediator instance = null;
	
	public static Map<String, BeanMethod> beanMethodMap = new ConcurrentHashMap<>();
	public Mediator() {}
	
	//双重检查锁DCL
	public static Mediator getInstance() {
		if(null==instance) {
			synchronized (Mediator.class) {
				if(null==instance) {
					instance = new Mediator();
				}
			}
		}
		return instance;
	}
	
	public Object processor(RpcRequest rpcRequest) {
		String key = rpcRequest.getClassName()+"."+rpcRequest.getMethodName(); 
		BeanMethod beanMethod = beanMethodMap.get(key);
		if(null==beanMethod) {
			return null;
		}
		Object bean = beanMethod.getBean();
		Method method = beanMethod.getMethod();
		try { 
			return method.invoke(bean, rpcRequest.getParams()); 
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
		 
	}
}
